package com.wtwd.campus.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.wtwd.campus.annotation.AuditLog;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.common.RespCode;
import com.wtwd.campus.entity.School;
import com.wtwd.campus.entity.SysUser;
import com.wtwd.campus.model.vo.PageDataVO;
import com.wtwd.campus.model.vo.ResultVO;
import com.wtwd.campus.model.vo.SchoolVO;
import com.wtwd.campus.service.*;
import com.wtwd.campus.utils.AuditLogUtils;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zdl
 * @since 2021-06-10
 */
@Api(tags = "学校管理")
@RestController
@RequestMapping("/school")
public class SchoolController {

    @Resource
    private SchoolService schoolService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysOrgService sysOrgService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private LogService logService;

    @ApiOperation(value = "查询学校分页数据", notes = "默认获取直属下级,选择同步下级后,获取所有下级")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页数", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "pageSize", value = "页大小", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "schoolName", value = "学校名称", dataType = "String")
            , @ApiImplicitParam(name = "orgId", value = "组织ID", dataTypeClass = Integer.class)
    })
    @GetMapping("/page")
    public ResultVO<PageDataVO<SchoolVO>> queryPage(@RequestParam(defaultValue = "1") Integer pageNo
            , @RequestParam(defaultValue = "10") Integer pageSize, String schoolName, Integer orgId) {
        IPage<SchoolVO> page = new Page<>(pageNo, pageSize);
        School school = new School();
        if (StringUtils.isNotBlank(schoolName)) {
            school.setSchoolName(schoolName);
        }
        // TODO 未指定组织id,则查询当前用户下所有数据
        if (orgId == null) {
            SysUser user = sysUserService.getCurrentLoginUser();
            school.setOrgCode(user.getOrgCode());
        } else {
            school.setOrgId(orgId);
        }
        return ResultVO.ok(schoolService.queryPage(page, school));
    }

    @ApiOperation("添加学校信息")
    @DynamicParameters(name = "addschoolModel", properties = {
            @DynamicParameter(name = "orgId", value = "组织ID", dataTypeClass = Integer.class, required = true)
            , @DynamicParameter(name = "orgCode", value = "组织编号", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "schoolName", value = "学校名称", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "phone", value = "负责任电话", dataTypeClass = String.class)
            , @DynamicParameter(name = "province", value = "省", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "city", value = "市", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "area", value = "区", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "eduStage", value = "教育阶段", dataTypeClass = String.class, required = true, example = "1-小学,2-初中,3-高中,4-其他")
    })
    @PostMapping("/schoolInfo")
    @AuditLog(operationType = "添加学校信息", operationContent = "", orgCode = "")
    public ResultVO add(@RequestBody JSONObject addschoolModel) {
        School school = JSONObject.toJavaObject(addschoolModel, School.class);
        ResultVO resultVo = schoolService.createSchool(school);
        if (resultVo.getCode() == RespCode.SUCCESS.getCode()) {
            Method method = null;
            try {
                method = SchoolController.class.getMethod("add", JSONObject.class);
                //获取操作的组织的code
                String orgCode = (String) addschoolModel.get("orgCode");
                String schoolName = (String) addschoolModel.get("schoolName");
                String operationContent = "新增学校：".concat(schoolName);
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return resultVo;
    }

    @ApiOperation("更新学校信息")
    @DynamicParameters(name = "updateSchoolModel", properties = {
            @DynamicParameter(name = "id", value = "学校Id", dataTypeClass = Integer.class, required = true)
            , @DynamicParameter(name = "schoolName", value = "学校名称", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "phone", value = "负责任电话", dataTypeClass = String.class)
            , @DynamicParameter(name = "province", value = "省", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "city", value = "市", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "area", value = "区", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "eduStage", value = "教育阶段", dataTypeClass = String.class, required = true, example = "1-小学,2-初中,3-高中,4-其他")
    })
    @PutMapping("/schoolInfo")
    @AuditLog(operationType = "更新学校信息", operationContent = "", orgCode = "")
    public ResultVO update(@RequestBody JSONObject updateSchoolModel) {
        School school = JSONObject.toJavaObject(updateSchoolModel, School.class);
        //根据学校id获取学校信息
        School school2 = logService.getSchoolById(school.getId());
        ResultVO resultVO = schoolService.updateSchool(school);
        if (resultVO.getCode() == RespCode.SUCCESS.getCode()) {
            Method method = null;
            try {
                method = SchoolController.class.getMethod("update", JSONObject.class);
                //获取操作的组织的code
                String orgCode = logService.getOrgCodeBySchoolId(school.getId());
                String schoolName = school.getSchoolName();
                String operationContent = "";
                if (!schoolName.equals(school2.getSchoolName())) {
                    operationContent = school2.getSchoolName().concat("更改为：").concat(schoolName);
                } else {
                    operationContent = "修改".concat(schoolName).concat("信息");
                }
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return resultVO;
    }

    @ApiOperation("删除学校信息")
    @ApiImplicitParam(name = "id", value = "学校id", required = true, dataTypeClass = Integer.class, paramType = "path")
    @ApiResponses({@ApiResponse(code = 1011, message = "该学校还存在年级")})
    @DeleteMapping("/schoolInfo/{id}")
    @AuditLog(operationType = "删除学校", operationContent = "", orgCode = "")
    public ResultVO delete(@PathVariable Integer id ) {
        //根据学校id获取学校信息
        School school = logService.getSchoolById(id);
        ResultVO resultVO = schoolService.deleteSchoolById(id);
        if (resultVO.getCode() == RespCode.SUCCESS.getCode()) {
            Method method = null;
            try {
                method = SchoolController.class.getMethod("delete", Integer.class);
                //获取操作的组织的code
                String orgCode = sysOrgService.getOrgCodeById(school.getOrgId());
                String operationContent = "删除学校：".concat(school.getSchoolName());
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return resultVO;
    }

    /**
     * 获取用户组织编码
     *
     * @param request
     * @return
     */
    public String getUserOrgCode(HttpServletRequest request) {
        //获取用户的组织编号
        String token = request.getHeader(Constants.HEADER_TOKEN_KEY);
        Map<String, Object> msg = redisService.getUserInfoByToken(token);
        String userMsg = (String) msg.get("user");
        JSONObject jsonObject = JSONObject.parseObject(userMsg);
        String userOrgCode = (String) jsonObject.get("orgCode");
        return userOrgCode;
    }
}

